package com.buaa.aimall.Utils.Client;

import com.buaa.aimall.Utils.Config.KongAPIGatewayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

@Component
public class KongAPIGatewayClient {

    private final KongAPIGatewayConfig kongAPIGatewayConfig;

    @Autowired
    public KongAPIGatewayClient(KongAPIGatewayConfig kongAPIGatewayConfig) {
        this.kongAPIGatewayConfig = kongAPIGatewayConfig;
    }

    public ResponseEntity<String> createServices(String name, String url) {
        String serviceUrl = UriComponentsBuilder.fromHttpUrl(kongAPIGatewayConfig.getServiceBaseUrl())
                .path("/services/")
                .build()
                .toUriString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("name", name);
        requestBody.add("url", url);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(serviceUrl, requestEntity, String.class);
    }

    public ResponseEntity<String> createRoutesForService(String serviceName) {
        String routeUrl = UriComponentsBuilder.fromHttpUrl(kongAPIGatewayConfig.getServiceBaseUrl())
                .path("/services/{serviceName}/routes")
                .buildAndExpand(serviceName)
                .toUriString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        String randomUUID = UUID.randomUUID().toString().substring(24);
        String name = serviceName + "_" + randomUUID;
        String paths = "/" + serviceName + "/" + randomUUID;

        requestBody.add("name", name);
        requestBody.add("paths", paths);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(routeUrl, requestEntity, String.class);
    }
}
